package com.example.mobile2021606129ly0608.util;

import android.os.Looper;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    public static OkHttpClient client;
    static {
        OkHttpClient.Builder builder=new OkHttpClient.Builder();
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15,TimeUnit.SECONDS);
        builder.connectTimeout(15,TimeUnit.SECONDS);
        client=builder.build();
    }
    public static JSONObject buidJSON(String [] keys ,Object... values){
        JSONObject jsonObject=null;
        try {
            jsonObject=new JSONObject();
            for (int i =0;i<keys.length;++i){
                jsonObject.put(keys[i],values[i]);
            }
        }catch (Exception e){
            jsonObject=null;
        }
        return jsonObject;
    }
public static RequestBody buildBody(JSONObject json){
        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"),
                json.toString());
}
public static  String host="http://121.9.253.237:8888/traffic/api/v2/";
    public static Request bulidRequest(String api,RequestBody body){
        return new Request.Builder().url(host+api).post(body).build();
    }
    public static Call buildCall(Request request){
        return client.newCall(request);
    }
    public static Handler handler=new Handler(Looper.getMainLooper());
    public interface AsynCallBack{
        void onFailure(Exception e);
        void onResponse(String json);
    }
    public static void asynRequest(final AsynCallBack callBack,String api,
                                    String[]keys,Object...values){
        JSONObject jsonObject=buidJSON(keys,values);
        RequestBody requestBody=buildBody(jsonObject);
        Request request=bulidRequest(api,requestBody);
        Call call=buildCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(e);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
             final String json=response.body().string();
             handler.post(new Runnable(){
                 @Override
                 public void  run(){
                     callBack.onResponse(json);
                 }

             });
            }
        });
    }
}
